package com.gimi.cloud.bbp.commonService.alipay.impl;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.apache.commons.codec.CharEncoding;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.gimi.cloud.bbp.common.constant.AliPayConstant;
import com.gimi.cloud.bbp.common.constant.RedisKeyConstant;
import com.gimi.cloud.bbp.common.enums.ResponseCodeEnum;
import com.gimi.cloud.bbp.common.exception.MsgException;
import com.gimi.cloud.bbp.commonService.alipay.AliPayService;
import com.gimi.cloud.bbp.commonService.redis.RedisService;

/**
 * 支付宝支付
 * 
 * @author 李林峰
 * @version 1.0
 * @Description
 * @create 2018年1月30日
 */
@Service
public class AliPayServiceImpl implements AliPayService {
	
	private static final Logger log = LoggerFactory.getLogger(AliPayServiceImpl.class);

	@Autowired RedisService redisService;

	@Override
	public AlipayTradeQueryResponse alipayTradeQuery(String out_trade_no, String trade_no) throws AlipayApiException {
		if (StringUtils.isAllBlank(out_trade_no, trade_no)) {
			throw new MsgException(ResponseCodeEnum.SERVICE_ERROR, "支付宝查询两个参数不能同时为空");
		}
		AlipayClient alipayClient = creatAlipayClient();
		
		AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();

		Map<String, String> tradeNoMap = new HashMap<>();
		tradeNoMap.put("out_trade_no", out_trade_no);
		tradeNoMap.put("trade_no", trade_no);
		
		request.setBizContent(JSON.toJSONString(tradeNoMap));
		AlipayTradeQueryResponse response = alipayClient.execute(request);
		if (response.isSuccess()) {
			return response;
		} else {
			throw new MsgException(ResponseCodeEnum.SERVICE_ERROR, "支付宝交易查询失败");
		}
	}
	
	@Override
	public AlipayClient creatAlipayClient(){
		log.info("读取配置表aliPayConfig,创建支付宝请求客户端");
		JSONObject aliPayConfig = redisService.getJSONObjectConfigByKey(RedisKeyConstant.ALI_PAY_CONFIG);
		JSONObject alipayClient = aliPayConfig.getJSONObject("AlipayClient");
		return new DefaultAlipayClient(AliPayConstant.SERVER_URL, alipayClient.getString("appId"),
				AliPayConstant.PRIVATE_KEY, alipayClient.getString("format"),CharEncoding.UTF_8, 
				AliPayConstant.ALIPAY_PUBLIC_KEY, AliPayConstant.SIGN_TYPE);
	}
	
	@Override
	public Map<String, String> alipayNotifyValidation(Map<String, String[]> requestParams) throws AlipayApiException {
		log.info("支付宝异步通知参数校验");
		Map<String,String> params = new HashMap<String,String>();
		for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
		    String name = iter.next();
		    String[] values = requestParams.get(name);
		    String valueStr = "";
		    for (int i = 0; i < values.length; i++) {
		        valueStr = (i == values.length - 1) ? valueStr + values[i]
		                    : valueStr + values[i] + ",";
		  	}
		    //乱码解决，这段代码在出现乱码时使用。
			//valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
			params.put(name, valueStr);
		}
		if (AlipaySignature.rsaCheckV1(params, AliPayConstant.ALIPAY_PUBLIC_KEY, CharEncoding.UTF_8
				,AliPayConstant.SIGN_TYPE)) {
			log.info("支付宝异步通知参数通过验证："+JSON.toJSONString(params));
			return params;
		}
		return null;
	}

}